package com.chatplus.application.aiprocessor.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * WebSocketSession的管理器
 *
 * @author chj
 * @date 2024/2/1
 **/
public class WebSocketManager {

    private WebSocketManager() {
    }

    // 保存 session 连接的地方
    private static final ConcurrentMap<String, WebSocketSession> SESSION_POOL = new ConcurrentHashMap<>();

    /**
     * 添加 session
     */
    public static void add(String key, WebSocketSession session) {
        SESSION_POOL.put(key, session);
    }

    /**
     * 删除并返回 session
     */
    public static WebSocketSession remove(String key) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        return SESSION_POOL.remove(key);
    }

    /**
     * 关闭连接的操作
     */
    public static void removeAndClose(String key) throws IOException {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        WebSocketSession session = remove(key);
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    /**
     * 获得 session
     */
    public static WebSocketSession get(String key) {
        return SESSION_POOL.get(key);
    }
}
